import threading
import time

import requests
import Boost_Python_TEST
import rust_http

a = []


def rust() -> str:
    """
    引用Rust HTTP自定义封装库, 并返回"Hello World"字符串
    """
    return rust_http.sum_as_string()


def raw_req() -> str:
    """
    原生请求方式
    """
    client = requests.session()
    return client.get("http://127.0.0.1:6677").text


def task_for_repeat_100(tag: str):
    """
    循环请求100次
    """
    for _ in range(100):
        start = time.time()

        if tag == "rust":
            result = rust()
        elif tag == "c++":
            result = Boost_Python_TEST.hello()
        else:
            result = raw_req()

        end = time.time()

        if result != "Hello World":
            raise Exception("Server service is not start")

        a.append(end - start)


def task_obj(tag):
    # 创建线程列表
    threads = []

    # 循环10次
    for _ in range(10):
        # 创建并启动5个线程, 每个线程循环请求100次
        for _ in range(5):
            thread = threading.Thread(target=task_for_repeat_100, args=(tag,))
            thread.start()
            threads.append(thread)

        # 等待所有线程完成
        for thread in threads:
            thread.join()

    a.sort()

    print("{}\n50%: {:.4f}\n75%: {:.4f}\n90%: {:.4f}\nmean: {:.4f}\n\n".format(tag, round(a[2500], 4),
                                                                               round(a[3750], 4),
                                                                               round(a[4500], 4),
                                                                               sum(a) / len(a)))


def main():
    global a
    task_obj("python")
    a.clear()

    # task_obj("rust")
    # a.clear()

    # task_obj("c++")


if __name__ == '__main__':
    main()
